<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
  </head>

  <body>
    <button id="btn">得到所有的省份数据</button>
    <script>
      let req;

      function getCommonHeaders() {
        return new Headers({
          a: 1,
          b: 2,
          cookie: "user=a",
        });
      }

      function getRequestInfo() {
        const url = "https://cnodejs.org/api/v1/topics";
        // get请求请求参数一般放到地址上，post请求一般放在body中

        const headers = getCommonHeaders();
        const config = {
          method: "get",
          headers,
          // body: JSON.stringify("a"),   // get/head中不能传递body，并且body类型需要和headers的content-type设置的类型一致
        };

        req = new Request(url, config);

        console.log(req.headers.has("Content-Type"));
        console.log(req.headers.get("a"));
        req.headers.append("cookies", "user=b");
        const keys = req.headers.keys();
        const values = req.headers.values();
        const entries = req.headers.entries();
        for (const key of keys) {
          console.log(key);
        }
        for (const value of values) {
          console.log(value);
        }
        return req.clone(); // 克隆一个全新的request对象，尽量每一次请求都创建一个新的request对象。
      }

      async function getProvince() {
        const req = getRequestInfo();
        const resp = await fetch(req);
        const pro = await getJSON(resp);
        console.log(pro);
      }

      async function getJSON(resp) {
        return await resp.json();
      }

      document.querySelector("#btn").onclick = function () {
        getProvince();
      };
    </script>
  </body>
</html>
